package com.hz.chendemo;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.OvershootInterpolator;
import android.widget.TextView;

import com.hjq.toast.ToastUtils;
import com.itheima.roundedimageview.RoundedImageView;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class PhoneFloatActivity extends Activity {

    public static String END_CALL = "END_CALL";


    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
    private static Context mContext = null;
    private static WindowManager mWindowManager = null;
    private static View mView = null;
    private String phoneNumber;

    private static final String LOG_TAG = "PhoneFloatActivity";
    public static Boolean isShown = false;
    TelephonyManager telMgr;
    private static final String MANUFACTURER_HTC = "HTC";

    private AudioManager audioManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_float);

        registEvenBusAction();


        Intent intent = getIntent();
        phoneNumber = intent.getStringExtra("incoming_number");

        if(phoneNumber != null){
            ToastUtils.show("INCOMM_CALL:"+phoneNumber);
        }

        telMgr = (TelephonyManager) this.getSystemService(Service.TELEPHONY_SERVICE);
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

        askForPermission();
    }

    //Evenbus 注册
    public void registEvenBusAction(){
        //     注册Evenbus 事件
        if(!EventBus.getDefault().isRegistered(this)){
            //注册事件
            EventBus.getDefault().register(this);
        }
    }

    public void unRegistEvenBusAction(){
        if(EventBus.getDefault().isRegistered(this)){
            //注册事件
            EventBus.getDefault().unregister(this);
        }
    }

    //定义处理接收的方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void userEventBus(String messageType) {

        if(messageType.equals(END_CALL)){
            hidePopupWindow();
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    /**
     * 请求用户给予悬浮窗的权限
     */
    public void askForPermission() {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,100);
            }
        }

        if (!Settings.canDrawOverlays(this)) {
            ToastUtils.show("当前无权限，请授权！");
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        } else {
            showPopupWindow();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                ToastUtils.show("权限授予失败，无法开启悬浮窗！");
            } else {
                ToastUtils.show("权限授予成功！");
                showPopupWindow();
            }

        }
    }

    public void showPopupWindow() {

        // 获取应用的Context
        mContext = this.getApplicationContext();
        // 获取WindowManager
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        mView = setUpView(this);

        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;

        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.x = 0 ;
        layoutParams.y = 20 ;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.format = PixelFormat.RGBA_8888 | PixelFormat.TRANSLUCENT;
        layoutParams.gravity = Gravity.TOP;

        mWindowManager.addView(mView, layoutParams);

        viewAnimation(1);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWindowManager.removeView(mView);
    }

    /**
     * 隐藏弹出框
     */
    public void hidePopupWindow() {
        if (null != mView) {
            mWindowManager.removeView(mView);
            this.finish();
        }
    }
    private void viewAnimation(int flag){
        if (null != mView) {
            ViewHelper.setTranslationY(mView,-100);
            ViewPropertyAnimator.animate(mView).translationY(0f).setDuration(750).setInterpolator(new OvershootInterpolator()).start();
        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        hidePopupWindow();
        return super.onKeyDown(keyCode, event);
    }

    private View setUpView(Context context) {

        View view = LayoutInflater.from(context).inflate(R.layout.in_call_layout, null);
        TextView callName = (TextView)view.findViewById(R.id.call_name);
        callName.setText(phoneNumber);

        TextView callDesc = (TextView)view.findViewById(R.id.call_desc);
        callDesc.setText("某某某公司技术总监,Happy Happy!");

        RoundedImageView callImage = (RoundedImageView)view.findViewById(R.id.call_icon);
        callImage.setImageResource(R.mipmap.ic_launcher);

        return view;
    }

}